import React, { Component } from 'react';
import {
  View,Text,StyleSheet,TextInput,TouchableHighlight,Modal,AsyncStorage,DeviceEventEmitter,
    Platform,
    Image
} from 'react-native';
import pxToDp from '../common/comm';
import ModalDropdown from 'react-native-modal-dropdown';
import {StackNavigator} from 'react-navigation';
import * as DATA from '../data/data';
import * as COMM from '../common/comm';

class Fanxian extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loginkey: null,
            money: '',
            isModal: false,
            chanpin:[],
            chanpinId:[],
            pid:'',
            chanpinName:'',
            item:[],
            itemName:'',
            iid:'',
            itemIds:[],
            defaultIndex:-1,
            isFanxian:false,//是否显示返现框,
            fanxian:0,
            isHasChanpin:false,//是否有产品list
        };
    }

    //提示框3秒后消失
    _show(txt) {
        this.setState({
            isModal: true,
            alertTxt: txt
        });
        this.timer = setTimeout(() => {this._hide()},3000);
    }

    _hide() {
        this.setState({
            isModal:false
        })
    }

    getItemList(index,value){
        this.setState({
            chanpinName:value,
            pid:this.state.chanpinId[index],
        });
        this.refs.item.select(-1);
        let _that = this;
        let arr = [];
        let arr1 = [];
        let data2 = 'loginkey='+this.state.loginkey+'&pid='+this.state.chanpinId[index];
        fetch(DATA.ITEMLIST_URL,{
            method: "POST",
            headers:{'Content-Type': 'application/x-www-form-urlencoded' },
            body: data2
        })
            .then((response) => {       // 数据解析方式
                if (response.ok) {
                    return response.json();
                }
            })
            .then((responseData) => {       // 获取到的数据处理
                if(responseData.sign == 1){
                    arr.push(responseData.list[0].name);
                    arr1.push(responseData.list[0].id);
                    _that.setState({
                        item:arr,
                        itemIds:arr1
                    })
                }
            })
            .catch((error) => { // 错误处理
                alert('获取数据失败!');
            })
            .done();
    }

    check_spfl() {
        //申请返利
        if (this.state.chanpinName == '') {
            this._show('请选择产品!');
            return false;
        }

        if (this.state.itemName == '') {
            this._show('请选择投资项目!');
            return false;
        }
        if (this.state.money == '') {
            this._show('请输入投资金额!');
            return false;
        }
        if (this.state.money < 100) {
            this._show('投资金额不低于100元!');
            return false;
        }
        if (isNaN(this.state.money)) {
            this._show('请输入数字！');
            return false;
        }
        return true;
    }

    _onPress(){
        let isCheck = this.check_spfl();
        if(isCheck){
            let _that = this;
            let data2 = 'loginkey='+this.state.loginkey+'&chanpin='+this.state.pid+'&item='+this.state.iid+'&money='+this.state.money;
            fetch(DATA.SAVEFANXIAN_URL,{
                method: "POST",
                headers:{'Content-Type': 'application/x-www-form-urlencoded' },
                body: data2
            })
                .then((response) => {       // 数据解析方式
                    if (response.ok) {
                        return response.json();
                    }
                })
                .then((responseData) => {       // 获取到的数据处理
                    if(responseData.status == 1){
                        // _that._show(responseData.msg);
                        _that.refs.select1.select(-1);
                        _that.refs.item.select(-1);
                        _that.setState({
                            money:'',
                            chanpinName:'',
                            itemName:'',
                            isFanxian:true,
                            fanxian:responseData.fanli
                        })
                    }
                })
                .catch((error) => { // 错误处理
                    alert('获取数据失败!');
                })
                .done();
        }
    }

    getData(){
        let _that = this;
        let data2 = 'loginkey='+ this.state.loginkey;
        fetch(DATA.CHANPINLIST_URL,{
            method: "POST",
            headers:{'Content-Type': 'application/x-www-form-urlencoded' },
            body: data2
        })
            .then((response) => {       // 数据解析方式
                if (response.ok) {
                    return response.json();
                }
            })
            .then((responseData) => {       // 获取到的数据处理
                if(responseData.status == 1){
                    if(responseData.list.length == 0){
                        return false;
                    }else{
                        let arr = [];
                        let arr1 = [];
                        for(let i=0;i<responseData.list.length;i++){
                            arr.push(responseData.list[i].name);
                            arr1.push(responseData.list[i].id);
                        }
                        _that.setState({
                            chanpinObj:responseData.list,
                            chanpin:arr,
                            chanpinId:arr1,
                            isHasChanpin:true
                        })
                        return true;
                    }
                }
            })
            .catch((error) => { // 错误处理
                alert('获取数据失败!');
            })
            .done();

    }

    componentWillUnMount() {
        DeviceEventEmitter.remove();
    }

    componentDidMount(){
        DeviceEventEmitter.addListener('product', (info)=>{
            this.setState({
                loginkey:info.loginkey
            });
            this.getData();
        });
        DeviceEventEmitter.addListener('logout', ()=>{
            this.setState({
                loginkey:null
            });
        });
        DeviceEventEmitter.addListener('tiaozhuan', ()=>{
            this.getData();
        });
    };

  static navigationOptions= {
      headerTintColor:'#fff',
      headerTitle: '申请返现',
      headerStyle: {
          backgroundColor: DATA.BASE_COLOR,
          height:Platform.OS === 'android'?pxToDp(84):pxToDp(110)
          },
      headerTitleStyle: {
          color: '#fff',
          fontSize: pxToDp(34),
          alignSelf:Platform.OS === 'android'?'center':null
          },
      gesturesEnabled :true
      }
  render() {
      let _that = this;
    return (
      <View style={styles.container}>
          {/*提示框*/}
          <Modal
              animationType='fade'            // 淡入淡出
              transparent={true}              // 透明
              visible={this.state.isModal}    // 根据isModal决定是否显示
              onRequestClose={() => {this.onRequestClose()}}  // android必须实现
          >
              <View style={modalStyle.modalViewStyle}>
                  <View style={modalStyle.hudViewStyle}>
                      <Text style={modalStyle.hudTextStyle}>{this.state.alertTxt}</Text>
                  </View>
              </View>
          </Modal>
          {/*返现框*/}
          <Modal
              animationType='fade'            // 淡入淡出
              transparent={true}              // 透明
              visible={this.state.isFanxian}    // 根据isModal决定是否显示
              onRequestClose={() => {this.onRequestClose()}}  // android必须实现
          >
              <View style={fanxian.modalViewStyle}>
                  <View style={fanxian.hudViewStyle}>
                      <Text style={fanxian.txt1}>提交成功，您的返利金额为</Text>
                      <View style={fanxian.box}>
                          <Text style={fanxian.money}>{this.state.fanxian}</Text>
                          <Text>元！</Text>
                      </View>
                      <Image style={fanxian.img} source={{uri:DATA.JINBI_IMG}}/>
                      <View style={fanxian.boxno}>
                          <Text
                              style={fanxian.iknow}
                              onPress={()=>{
                                  this.setState({
                                      isFanxian:false
                                  })
                              }}
                          >我知道了</Text>
                      </View>
                  </View>
              </View>
          </Modal>
        <View style={styles.row}>
          <Text style={styles.em}>*</Text>
          <Text style={styles.myFontSize}>请选择投资产品: </Text>
          <ModalDropdown
            textStyle={styles.btnText}
            ref="select1"
            enableEmptySections={true}
            style={styles.btn}
            dropdownStyle={styles.down}
            onDropdownWillShow={()=>{
                if(this.state.loginkey === null){
                    this._show('请登录');
                    return false;
                }else if(!this.state.isHasChanpin){
                    this._show('请先投资，再申请！');
                    return false;
                }
            }}
            onSelect={(index,value)=>{
                _that.getItemList(index,value);
            }}
            defaultValue='请选择投资产品...'
            options={this.state.chanpin}
          />
        </View>
        <View style={styles.row}>
          <Text style={styles.em}>*</Text>
          <Text style={styles.myFontSize}>请选择投资项目: </Text>
          <ModalDropdown
            textStyle={styles.btnText}
            enableEmptySections={true}
            ref='item'
            style={styles.btn}
            dropdownStyle={styles.down}
            onDropdownWillShow={()=>{
                if(this.state.loginkey === null){
                    this._show('请登录');
                    return false;
                }else if(!this.state.isHasChanpin){
                    this._show('请先投资，再申请！');
                    return false;
                }
            }}
            onSelect={(index,value)=>{
                _that.setState({itemName:value,iid:_that.state.itemIds[index]})
            }}
            defaultValue='请选择投资项目...'
            defaultIndex={this.state.defaultIndex}
            options={this.state.item}
          />
        </View>
        <View style={[styles.row,{borderBottomWidth:0}]}>
          <Text style={styles.em}>*</Text>
          <Text style={styles.myFontSize}>投资金额（元）:</Text>
          <TextInput
            keyboardType='numeric'
            style={styles.myTextInput}
            placeholder='请输入投资金额'
            placeholderTextColor='transparent'
            onChangeText={(text)=>{
                this.setState({money:text})
            }}
            value={this.state.money}
          />
        </View>
        <Text style={styles.text}>提交申请后，我们会在下一个工作日进行审核并返现。请关注您的伏蒙余额。</Text>
        <Text style={styles.submit} onPress={this._onPress.bind(this)}>提交</Text>
      </View>
    );
  }
}

export default Fanxian = StackNavigator({
  Fanxian:{
    screen:Fanxian
  }
})

const styles = StyleSheet.create({
  container: {
    marginTop: pxToDp(20),
    backgroundColor: '#fff',
    height:pxToDp(897),
    alignItems:'center'
  },
  row: {
    width:pxToDp(640),
    paddingTop: pxToDp(20),
    paddingBottom: pxToDp(20),
    flexDirection: 'row',
    borderBottomWidth: 1,
    borderBottomColor:'#e3e3e3'
  },
  myFontSize: {
    fontSize: pxToDp(30),
    fontWeight:'bold'
  },
  em:{
    color: 'red',
    marginLeft:pxToDp(30)
  },
  btn: {
    width: pxToDp(335),
    borderWidth: 1,
    borderColor: '#a3a3a3',
    paddingLeft: pxToDp(5),
    borderRadius:pxToDp(10)
  },
  btnText: {
    fontSize: pxToDp(24),
    color:'#a3a3a3'
  },
  down: {
    width:pxToDp(330)
  },
  myTextInput: {
    width: pxToDp(365),
      height:Platform.OS === 'android'?null:pxToDp(50),
    marginTop: Platform.OS === 'android'?-pxToDp(20):-pxToDp(5),
    paddingLeft:pxToDp(10),
    fontSize:pxToDp(24),
  },
  text: {
    width: pxToDp(550),
    textAlign: 'center',
    color: 'red',
    marginTop:pxToDp(30)
  },
  submit: {
    width: pxToDp(400),
    height: pxToDp(70),
    backgroundColor: DATA.BASE_COLOR,
    color: '#fff',
    textAlign: 'center',
    borderRadius: pxToDp(20),
      paddingTop:Platform.OS === 'android'?null:pxToDp(20),
      textAlignVertical:'center',
    fontSize: pxToDp(34),
    marginTop:pxToDp(100)
  }
});

const modalStyle = StyleSheet.create({
    modalViewStyle: {
        position: 'absolute',
        top:pxToDp(900),
        alignSelf:'center'
    },
    hudViewStyle: {
        backgroundColor: 'rgba(0,0,0,0.5)',
        paddingLeft:pxToDp(15),
        paddingRight:pxToDp(15),
        paddingTop:pxToDp(10),
        paddingBottom: pxToDp(10),
        borderRadius:pxToDp(10)
    },
    hudTextStyle: {
        color:'#fff'
    }
})

const fanxian = StyleSheet.create({
    modalViewStyle:{
        alignItems:'center',
        justifyContent:'center',
        width:pxToDp(640),
        height:pxToDp(1200),
        backgroundColor:"rgba(0,0,0,0.5)",
    },
    hudViewStyle: {
        backgroundColor:'#fff',
        width:pxToDp(400),
        height:pxToDp(550),
        borderRadius:pxToDp(30),
        paddingTop:pxToDp(70),
        paddingLeft:pxToDp(30),
        paddingRight:pxToDp(30),
        alignItems:'center'
    },
    txt1:{
        marginBottom:pxToDp(10)
    },
    box:{
        flexDirection:'row',
        alignItems:'center'
    },
    money:{
        fontSize:pxToDp(60),
        color:'#36ad50'
    },
    img:{
        width:pxToDp(200),
        height:pxToDp(200),
        marginBottom:pxToDp(20)
    },
    boxno:{
        backgroundColor:DATA.BASE_COLOR,
        width:pxToDp(300),
        height:pxToDp(70),
        borderRadius:pxToDp(20),
        justifyContent:'center',
        alignItems:'center'
    },
    iknow:{
        color:'#fff',
        fontSize:pxToDp(28)
    }
})